import {useMutation, useQuery, useQueryClient} from "@tanstack/vue-query";
import {organizationApi} from "@/api/sys/organization.js";


export const useSysOrganizationTree = () => {
    return useQuery({
        queryKey: ["sysOrganizationTree"],
        queryFn: () => organizationApi.tree(),
        // 缓存时间5分钟
        staleTime: 5 * 60 * 1000,
    })
}

// listByParentCode
export const useSysOrganizationListByParentCode = (parentCodeRef) => {
    return useQuery({
        queryKey: computed(() => ["sysOrganizationListByParentCode", parentCodeRef.value?.parentCode]),
        queryFn: () => organizationApi.listByParentCode(parentCodeRef.value?.parentCode === '-' ? null : parentCodeRef.value?.parentCode),
        // 缓存时间5分钟
        staleTime: 5 * 60 * 1000,
        enabled: computed(() => !!parentCodeRef.value?.parentCode)
    })
}

// getById
export const useSysOrganizationById = (idRef) => {
    return useQuery({
        queryKey: computed(() => ["sysOrganizationById", idRef.value]),
        queryFn: () => organizationApi.getById(idRef.value),
        // 缓存时间5分钟
        staleTime: 5 * 60 * 1000,
        enabled: computed(() => !!idRef.value)
    })
}

// 增删改查
export const useSysOrganizationMutations = () => {
    const queryClient = useQueryClient()

    // 缓存失效统一方法
    const invalidateOrganizationCaches = async (id) => {
        // 刷新组织架构树
        await queryClient.invalidateQueries({queryKey: ['sysOrganizationTree'], exact: false});
        // 刷新按父节点编码查询的列表
        await queryClient.invalidateQueries({queryKey: ['sysOrganizationListByParentCode'], exact: false});
        // 刷新单条组织架构详情（如果提供了 id）
        if (id) {
            await queryClient.invalidateQueries({queryKey: ['sysOrganizationById', id]});
        }
    };

    // delete /{id:\d+}
    const deleteById = useMutation({
        mutationFn: (id) => organizationApi.delete(id),
        onSuccess: async (_, id) => {
            await invalidateOrganizationCaches(id);
        }
    })

    // 批量删除
    const deleteBatch = useMutation({
        mutationFn: (ids) => organizationApi.deleteBatch(ids),
        onSuccess: async () => {
            await invalidateOrganizationCaches();
        }
    })

    // create
    const create = useMutation({
        mutationFn: (data) => organizationApi.create(data),
        onSuccess: async () => {
            await invalidateOrganizationCaches();
        }
    })

    // update
    const update = useMutation({
        mutationFn: (data) => organizationApi.update(data),
        onSuccess: async (_, data) => {
            await invalidateOrganizationCaches(data.id);
        }
    })

    return {deleteById, deleteBatch, create, update}
}